package com.atguigu.gmall.activity.controller;

import com.atguigu.gmall.activity.redis.CacheHelper;
import com.atguigu.gmall.activity.service.ActivityService;
import com.atguigu.gmall.activity.util.DateUtil;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.product.client.common.constant.RedisConst;
import com.atguigu.gmall.product.client.common.result.Result;
import com.atguigu.gmall.product.client.common.result.ResultCodeEnum;
import com.atguigu.gmall.product.client.common.util.AuthContextHolder;
import com.atguigu.gmall.product.client.common.util.MD5;
import com.atguigu.gmall.product.client.model.activity.SeckillGoods;
import com.atguigu.gmall.product.client.model.activity.UserRecode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;

@RestController
@RequestMapping("/api/activity/seckill")
public class SecKillApiController {

    public static final String salt="sadas";

    @Autowired
    private ActivityService activityService;
    @Autowired
    private RabbitService rabbitService;

    //获取抢购码
    @GetMapping("/auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable Long skuId, HttpServletRequest request){

        String userId = AuthContextHolder.getUserId(request);
        SeckillGoods seckillGoods = activityService.findBySkuId(skuId);
        //1. 是否在活动时间
        Date startTime = seckillGoods.getStartTime();  //活动开始时间
        Date endTime = seckillGoods.getEndTime();   //活动结束时间
        Date curTime = Calendar.getInstance().getTime();   //当前时间
        if (DateUtil.dateCompare(startTime,curTime) && !DateUtil.dateCompare(endTime,curTime)){
            //抢购码
            String encrypt = MD5.encrypt(salt + userId);
            return Result.ok(encrypt);
        }else{
            return Result.fail().message("不在活动时间范围内");
        }
        //2. 审核是否通过
        //3. 剩余库存是否大于0
    }

    //开始秒杀
    @PostMapping("/auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable Long skuId, String skuIdStr, HttpServletRequest request){

        String userId = AuthContextHolder.getUserId(request);
        //1. 校验抢购码
        String encrypt = MD5.encrypt(salt + userId);
        if (!encrypt.equals(skuIdStr)){
            return Result.fail().message("抢购码失败");
        }
        //2. 校验状态码
        Object status = CacheHelper.get(skuId.toString());
        if (!"1".equals(status)){
            return Result.build(null, ResultCodeEnum.SECKILL_FINISH);
        }
        //3. 发消息
        UserRecode userRecode = new UserRecode();
        userRecode.setSkuId(skuId);
        userRecode.setUserId(userId);
        rabbitService.sendMessage(
                MqConst.EXCHANGE_DIRECT_SECKILL_USER,
                MqConst.ROUTING_SECKILL_USER,
                userRecode);
        return Result.ok();
    }


    //检查结果
    //1. 商品信息 2. 库存信息  3. 用户过来没  4. 抢购资格  5. 用户下的单
    @GetMapping("/auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable Long skuId,HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        //1. 检查5
        Object o1 = redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS_USERS + userId);
        if (o1 != null){
            return Result.build(null,ResultCodeEnum.SECKILL_ORDER_SUCCESS);  //下单成功
        }
        //2. 检查4
        Object o2 = redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS + userId);
        if (o2 != null){
            return Result.build(null,ResultCodeEnum.SECKILL_SUCCESS);  //抢单成功
        }
        //3. 检查3
        Object o3 = redisTemplate.opsForValue().get(RedisConst.SECKILL_USER+ userId);
        if (o3 == null ){
            //用户没有来过
            Object o4 = CacheHelper.get(skuId.toString());
            if ("1".equals(o4)){
                return Result.build(null,ResultCodeEnum.SECKILL_RUN);  //正在排队
            }
        }
        //没有抢到
        return Result.build(null,ResultCodeEnum.SECKILL_FAIL);   //抢单失败
    }
    @Autowired
    private RedisTemplate redisTemplate;

}
